import sys, os, subprocess, signal, logging


from twisted.scripts import twistd
from twisted.python import usage

class Options(twistd.ServerOptions):
    defaultSubCommand = 'meercat-nevow'
    synopsis = "Usage: meercat-nevow [options]"

def run():
    twistd.app.run(twistd.runApp, Options)


def simple_usage():
    print >> sys.stderr, "Usage: %s [start|stop|restart|fg|debug]" % (sys.argv[0],)
    return 1

def start(options):
    twistd.runApp(options)
    return 0

def stop(options):
    if not options['pidfile']:
        return 1
    
    if not os.path.exists(options['pidfile']):
        print '%s is not running' % (str(sys.argv[0]),)
        return 1
    
    try:
        pid = int(open(options['pidfile']).read())
    except:
        print "No pid found?"
        return 1
    
    try:
        os.kill(pid,signal.SIGTERM)
        print "Sent signal %s to pid %s" % (str(signal.SIGTERM),str(pid),)
        results = os.waitpid(pid, os.WUNTRACED)
        print "Waited for pid, %s" % (str(pid),)

        if os.WIFSTOPPED(results[1]):
            return 0
        return results[1]
    except Exception, e:
      print "Exception: %s" % (str(e),)
      return 1

def run_with_options(options):
    try:
        if len(sys.argv) < 2:
            sys.exit(simple_usage())
        
        action = str(sys.argv[1]).strip().lower()
        
        if action not in ('start','stop','restart','fg','debug',):
            sys.exit(simple_usage())
        
        config = twistd.ServerOptions()
        config.parseOptions(options)
        
        if action == 'fg':
            config['nodaemon'] = True
        
        if action == 'debug':
            print 'debug'
            config.opt_debug()
            config['nodaeomon'] = True
        
        if action in ('start','fg','debug',):
            print 'starting'
            sys.exit(start(config))
        elif action == 'stop':
            sys.exit(stop(config))
        elif action == 'restart':
            if stop(config) == 0:
                sys.exit(start(config))
            sys.exit(1)
        else:
            sys.exit(simple_usage())
    except SystemExit, e:
        # calls to sys.exit() raise this error :(
        pass
    except:
        # all other exceptions get caught here
        extype, value = sys.exc_info()[:2]
        print >> sys.stderr, "ERROR: %s (%s)" % (extype, value)
        # return 1 for "general error"
        sys.exit(1)